/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package heartsserver;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Random;
import java.util.Stack;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author quangduc
 */
public class Server implements Runnable {

    ThreadServer clients[] = new ThreadServer[50];
    ServerSocket server = null;
    Thread thread = null;
    int clientCount = 0;
    int entireSlot = 1;
    ArrayList<String> vTapTin;
    public static ArrayList<Player> vPlayer;
    int VongChoi = 0;
    int soLanDanhBai = 1;
    ArrayList<Card> lstDoiBai = new ArrayList<>();
    ArrayList<Card> vCard = new ArrayList<>(); //Khoi tao bo bai 52 la   
    String sentMsg = "6 1 ";
    int soBaiTrenBan = 0;
    int[] dsDiem = new int[4];
    public static Vector<String> dsMathPlayer = new Vector<String>();
    int DemDiem = 0;
    int diemMax = 50;
    boolean maxDiem = false;
    int tiepTucChoiBai = 0;
    CauHinh cauhinh;

    /**
     * @param args the command line arguments
     */
//    public static void main(String[] args) {
//        // TODO code application logic here
//        Server server = null;
//        server = new Server(8999);
//    }
    public Server(int port,CauHinh cauhinh) {
        vTapTin = new ArrayList<>();
        try {
            this.cauhinh = cauhinh;
            InetAddress ipAddress = InetAddress.getLocalHost();
            System.out.println("Binding to port " + port + ", please wait  ...");
            server = new ServerSocket(port, 0, ipAddress);
            System.out.println("Server started: " + server);
            start();
        } catch (IOException ioe) {
            System.out.println("Can not bind to port " + port + ": " + ioe.getMessage());
        }

        vPlayer = new ArrayList<Player>();
    }

    private void addThread(Socket socket) {
        if (clientCount < clients.length) {
            System.out.println("Client accepted: " + socket);
            clients[clientCount] = new ThreadServer(this, socket);
            try {
                clients[clientCount].open();
                clients[clientCount].start();
                clientCount++;
                if (clientCount == 4) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    XuLyChiaBai(Define.START, "5 1");
                    lstDoiBai.clear();
                }


            } catch (IOException ioe) {
                System.out.println("Error opening thread: " + ioe);
            }
        } else {
            System.out.println("Client refused: maximum " + clients.length + " reached.");
        }
        System.out.println("Client name: " + clients[clientCount - 1].getName());
    }

    public void start() {
        if (thread == null) {
            thread = new Thread(this);
            System.out.println(thread);
            thread.start();
        }
    }

    public void stop() {
        if (thread != null) {
            thread.stop();
            thread = null;
        }
    }
    //Tim client

    private int findClient(int ID) {
        for (int i = 0; i < clientCount; i++) {
            if (clients[i].getId() == ID) {
                return i;
            }
        }
        return -1;
    }

    //Ham buoi: Cap nhat lai bo bai da chia cho nhungw ngoif choi nao
    private void ThemLaBai(int iPlayerID, String BaiDuocChia) {
        String s[] = BaiDuocChia.split(" ");
        for (int i = 0; i < s.length; i = i + 2) {
            Card c = new Card(
                    Integer.valueOf(s[i]),
                    Integer.valueOf(s[i + 1]),
                    iPlayerID);
            vCard.add(c);
        }

    }

    public void XuLyChiaBai(int ID, String input) {
        System.out.println("message receive:" + input);
        if ((input == null ? "" != null : !input.equals(""))
                && input != null) {

            String[] parameterArray = input.split(" ");
            int code = Integer.parseInt(parameterArray[0]);


            switch (code) {
                case 1:
                    tiepTucChoiBai++;
                    if(tiepTucChoiBai >=4){
                        tiepTucChoiBai = 0;
                        XuLyChiaBai(1, "5 1");
                    }
                    break;
                case 2://Cập nhật kết quả
                    int playerId = Integer.parseInt(parameterArray[1]);
                    int diemSo = Integer.parseInt(parameterArray[2]);
                    System.out.println("\nDiem moi cua player " + playerId + ": " + diemSo);
                    dsDiem[playerId] += diemSo;
                    if (dsDiem[playerId] > diemMax) {
                        maxDiem = true;
                    }
                    soLanDanhBai++;
                    if (soLanDanhBai > 13) {
                        soLanDanhBai = 0;
                        if (maxDiem == true) {
                            String msg = "5 " + VongChoi;
                            for (int i = 0; i < 4; i++) {
                                msg += " " + dsDiem[i];
                            }
                            for (int i = 0; i < 4; i++) {
                                System.out.println("\nBang Diem: " + msg);
                                clients[i].send(msg);
                            }
                        } else {
                            XuLyChiaBai(1, "5 1");
                        }
                    } else {
                        System.out.println("\nPlayer " + playerId + " ra bai");
                        clients[playerId].send("6 " + playerId);
                    }

//                    DemDiem++;
//
//                    if (playerId == 0) {
//                        dsDiem[0] = diemSo;
//                    }
//                    if (playerId == 1) {
//                        dsDiem[1] = diemSo;
//                    }
//                    if (playerId == 2) {
//                        dsDiem[2] = diemSo;
//                    } else {
//                        dsDiem[3] = diemSo;
//                    }

//                    String s = VongChoi + " " + String.valueOf(dsDiem[0]) + " "
//                            + String.valueOf(dsDiem[1]) + " "
//                            + String.valueOf(dsDiem[2]) + " "
//                            + String.valueOf(dsDiem[3]);
//
//                    if (DemDiem == 13) {
//                        System.out.println("\nIn diem");
//                        dsMathPlayer.add(s);
//                        DemDiem = 0;
//                        frmDiem frm = new frmDiem();
//                        frm.setVisible(true);
//                    }                    


                    break;
                case 26:
                    String message = "25 " + vPlayer.size();
                    for (int i = 0; i < vPlayer.size(); i++) {
                        message = message + " "
                                + vPlayer.get(i).NamePlayer
                                + " " + vPlayer.get(i).imgPath;
                    }
                    break;

                case 3:
                    if (vPlayer.size() < 4) {
                        String name = parameterArray[1];
                        String path = parameterArray[2];
                        Player player = new Player(name, path, 0);
                        player.Iphost = vPlayer.size() + 1;
                        vPlayer.add(player);

                        // clients[findClient(ID)].send("4 1 " + this.entireSlot);
                        this.entireSlot++;
                        System.out.println("So can tim: " + vPlayer.size());

                    } else {
                        // clients[findClient(ID)].send("4 0");
                    }
                    break;
                case Define.START:
                    VongChoi++;
                    soBaiTrenBan = 0;
                    //Khoi tao bo bai
                    System.out.println("\nChia bai nao");
                    /*
                     *0: Hai
                     * 1: Ba
                     * 2: Bon
                     * 3: Nam
                     * 4: Sau
                     * 5: Bay
                     * 6: Tam
                     * 7: Chin
                     * 8: Mười
                     * 9: Bồi
                     * 10: Đầm
                     * 11: Già 
                     * 12: Át
                     * Cơ: 3, Rô: 2, Chuồn: 1, Bích: 0
                     */
                    String[] QuanBai = {"0", "1", "2", "3", "4", "5",
                        "6", "7", "8", "9", "10", "11", "12"};
                    //13 quan bai tuong ung
                    String[] Chat = {"0", "1", "2", "3"}; //Co = 3, Ro = 2 Chuon = 1, Bich = 0
                    String[] Bo_Bai = new String[QuanBai.length * Chat.length];


                    int n = 0;
                    for (int i = 0; i < QuanBai.length; i++) {
                        for (int j = 0; j < Chat.length; j++) {
                            Bo_Bai[n] = QuanBai[i] + " " + Chat[j];

                            n++;
                        }
                    }

                    System.out.println("\nKet thuc chia");
                    //Xao bai
                    Random generator = new Random();

                    for (int i = 0; i < 27624; i++) {
                        int random = generator.nextInt(52);
                        String[] temp = new String[Bo_Bai.length];

                        // copy tu 0 -> random ve cuoi mang temp
                        int k = temp.length - 1;
                        for (int j = 0; j < random; j++) {
                            temp[k] = Bo_Bai[j];
                            k--;
                        }

                        //copy tu random -> soloai.length ve dau mang temp
                        int y = 0;
                        for (int x = random; x < Bo_Bai.length; x++) {
                            temp[y] = Bo_Bai[x];
                            y++;
                        }
                        //luu lai ket qua vao mang soloai
                        System.arraycopy(temp, 0, Bo_Bai, 0, Bo_Bai.length);
                    }

                    //Chia bai
                    int playerID = 0;
                    int startPlayer = 0;
                    int start = 0;
                    int end = 13;

                    //tim xem thang nao co con 2 nhep thi cho no lam startPlayer
//                    for (int t = 0; t < 52; t++) {
//                        if (Bo_Bai[t].compareTo("0 1") == 0) {
//                            startPlayer = t / 13;
//                            System.out.println("\nPlayer cam 2 nhep: " + startPlayer);
//                            //Gui thong bao toi nguoi choi nay
//                            clients[startPlayer].send("6 " + startPlayer);
//                            break;
//                        }
//                    }

                    for (int x = 0; x < 4; x++) {
                        String baiDuocChia = "";
                        for (int i = start; i < end; i++) {
                            baiDuocChia += Bo_Bai[i] + " ";
                        }
                        try {
                            //Chia bai
                            clients[playerID].send("6 " + playerID + " " + baiDuocChia);

                            //Them la bai cho nguoi choi
                            ThemLaBai(playerID, baiDuocChia);
                            //Gui xuong vong dang choi
                            clients[playerID].send("8 " + VongChoi);
                            //bai chia cho nguoi 1
                            System.out.println("\nBai chia cho nguoi " + playerID + ": "
                                    + baiDuocChia);
                            start = end;
                            end += 13;
                            //Hien thi tung nguoi choi
                            //Kiem tra co cam 2 nhep k
                            playerID++;
                        } catch (Exception ex) {
                            System.out.println("\nKhong du nguoi");
                        }
                    }

                    //Ket qua chia bai cho nguoi choi
//                    System.out.println("\nIn xem thu bo bai\n");
//                    for (int i = 0; i < vCard.size(); i++) {
//                        System.out.println(vCard.get(i).getNumber()
//                                + " " + vCard.get(i).getType() + " "
//                                + vCard.get(i).getPlayer());
//                    }
                    break;

                case 7:
                    sentMsg = "7";//Thông báo tới lượt đi
                    int nguoidanh = Integer.parseInt(parameterArray[1]);
                    int nguoiketiep = -1;
                    //kiem tra nguoi ke tiep
                    if (nguoidanh < 3) {
                        nguoiketiep = nguoidanh + 1;
                    } else {
                        nguoiketiep = 0;
                    }
                    sentMsg += " " + nguoidanh;
                    for (int i = 2; i < parameterArray.length; i++) {
                        sentMsg += " " + parameterArray[i];
                    }
                    for (int i = 0; i < 4; i++) {
                        if (i != nguoidanh) {
                            System.out.println("\nGui hien thi bai cho player " + i + " : " + sentMsg);
                            clients[i].send(sentMsg);
                        }
                    }
                    soBaiTrenBan++;
                    //Khi số bài đủ 4 lượt đi sẽ thuộc về người thắng
                    if (soBaiTrenBan >= 4) {//có 4 lá trên bàn
                        //Thông báo player tới lượt   
                        soBaiTrenBan = 0;
                    } else {//Không đủ 4 lá sẽ tới lượt người kế tiếp đi
                        //Thông báo player tới lượt  
                        clients[nguoiketiep].send("6 " + nguoiketiep);
                        System.out.println("\nLuot Ke Tiep: 6 " + nguoiketiep);
                    }
                    break;

                case Define.CHAT_MSG_SERVER: {
                    String name = parameterArray[1];
                    String message10 = "";
                    for (int i = 2; i < parameterArray.length; i++) {
                        message10 += parameterArray[i] + " ";
                    }

                    for (int i = 0; i < clientCount; i++) {
//                        clients[i].send("12 " + name + " " + message10);
                    }
                    break;
                }

                case Define.HAI_MESSAGE:
                    String message12 = input.substring(2);
                    for (int i = 0; i < clientCount; i++) {
//                        clients[i].send("14 " + message12);
                    }
                    break;

                case 12: //Doi bai
                    int nguoiDua = Integer.valueOf(parameterArray[1]);
                    int NguoiNhan = 0;
                    System.out.println("Vong choi: " + VongChoi
                            + " Nguoi dua: " + nguoiDua);
                    switch (VongChoi) {
                        case 1:
                            NguoiNhan = (nguoiDua + 1) % 4;
                            break;
                        case 2:
                            NguoiNhan = (nguoiDua + 3) % 4;
                            break;
                        case 3:
                            NguoiNhan = (nguoiDua + 2) % 4;
                            break;

                    }
                    String[] BaiGuiXuong = new String[7];
                    System.out.println("Vi tri bat dau:" + parameterArray[2]);
                    System.arraycopy(parameterArray, 2, BaiGuiXuong,
                            0, BaiGuiXuong.length - 1);

                    //Dua vao mang la bai
                    for (int i = 0; i < BaiGuiXuong.length - 1; i = i + 2) {
                        Card c = new Card(
                                Integer.valueOf(BaiGuiXuong[i]),
                                Integer.valueOf(BaiGuiXuong[i + 1]),
                                NguoiNhan);
                        lstDoiBai.add(c);
                    }
                    System.out.println("Mang bai:");
                    for (int i = 0; i < lstDoiBai.size(); i++) {
                        System.out.println("a: " + lstDoiBai.get(i).getPlayer()
                                + " " + lstDoiBai.get(i).getNumber()
                                + " " + lstDoiBai.get(i).getType());
                    }
                    //Dax guiwr du
                    if (lstDoiBai.size() >= 12) {
                        //Gui laij bai xuong tung ung voi tung playID
                        String Gui0 = "";
                        String Gui1 = "";
                        String Gui2 = "";
                        String Gui3 = "";
                        for (int i = 0; i < lstDoiBai.size(); i++) {
                            if (lstDoiBai.get(i).getPlayer() == 0) {
                                Gui0 += lstDoiBai.get(i).getNumber()
                                        + " " + lstDoiBai.get(i).getType() + " ";
                            }
                            if (lstDoiBai.get(i).getPlayer() == 1) {
                                Gui1 += lstDoiBai.get(i).getNumber()
                                        + " " + lstDoiBai.get(i).getType() + " ";
                            }
                            if (lstDoiBai.get(i).getPlayer() == 2) {
                                Gui2 += lstDoiBai.get(i).getNumber()
                                        + " " + lstDoiBai.get(i).getType() + " ";;
                            }
                            if (lstDoiBai.get(i).getPlayer() == 3) {
                                Gui3 += lstDoiBai.get(i).getNumber()
                                        + " " + lstDoiBai.get(i).getType() + " ";;
                            }
                        }
                        //Xoa lstDoiBai
                        lstDoiBai.clear();
                        //Gui xuong cliet tuong ung
                        clients[0].send("12 0 " + Gui0);
                        clients[1].send("12 1 " + Gui1);
                        clients[2].send("12 2 " + Gui2);
                        clients[3].send("12 3 " + Gui3);
                        //Gui lenh 
                        System.out.println("Gui 0: " + "12 0 " + Gui0);
                        System.out.println("Gui 1: " + "12 1 " + Gui1);
                        System.out.println("Gui 2: " + "12 2 " + Gui2);
                        System.out.println("Gui 3: " + "12 3 " + Gui3);


                    }
                    break;

            }

        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                if (clientCount < 4) {
                    addThread(server.accept());
                    System.out.println("\nCho connect:" + entireSlot + " " + sentMsg);
                }
                //throw new UnsupportedOperationException("Not supported yet.");
            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
}
